import json
from datetime import timedelta

import shortuuid

from ..extensions import redis_store


class SessionService(object):
    @classmethod
    def create_local_token(cls, local_auth):
        profile_id = local_auth.auth.profile_id
        from hashlib import sha256
        impl = sha256()
        impl.update((profile_id + shortuuid.uuid()).encode())
        access_token = impl.hexdigest()
        impl.update((profile_id + shortuuid.uuid()).encode())

        refresh_token = impl.hexdigest()

        return cls.save_token(access_token=access_token,
                              refresh_token=refresh_token,
                              user_id=profile_id,
                              user_type=local_auth.type)

    @classmethod
    def get_token(cls, access_token=None, refresh_token=None):
        token_data = None
        if access_token :
            access_token_id = cls._create_access_token_id(access_token)
            token_data = redis_store.get(access_token_id)
        if not token_data and refresh_token:
            refresh_token_id = cls._create_refresh_token_id(refresh_token)
            token_data = redis_store.get(refresh_token_id)

        if token_data: return json.loads(token_data.decode())

    @classmethod
    def save_token(cls, *args, **kwargs):
        token_data = json.dumps(kwargs)

        if 'access_token' in kwargs:
            access_token_id = cls._create_access_token_id(kwargs.get('access_token'))
            expires_in = kwargs.get('expires_in', 3600)
            redis_store.setex(access_token_id, token_data, timedelta(seconds=expires_in))
        if 'refresh_token' in kwargs:
            refresh_token_id = cls._create_refresh_token_id(kwargs.get('refresh_token'))
            redis_store.setex(refresh_token_id, token_data, timedelta(days=7))
        return kwargs
            #
            # tok.access_token = token['access_token']
            # tok.refresh_token = token['refresh_token']
            # tok.token_type = token['token_type']
            # tok.scopes = token['scope'].split()
            # tok.expires = expires
            # tok.user = request.user
            #
            # tok_data = tok.dump_data()
            # redis_store.setex(access_token_id, timedelta(seconds=expires_in), tok_data)
            # redis_store.setex(refresh_token_id, timedelta(days=7), tok_data)

    @classmethod
    def _create_access_token_id(cls, token):
        return 'access_token.{}'.format(token)

    @classmethod
    def _create_refresh_token_id(cls, token):
        return 'refresh_token.{}'.format(token)
